package org.xbdframework.boot.autoconfigure.task;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.task.TaskExecutorCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * TaskExecutor自动化配置
 *
 * @author luas
 * @since 1.5.0
 */
@ConditionalOnClass(ThreadPoolTaskExecutor.class)
@Configuration
@EnableConfigurationProperties(XbdTaskExecutionProperties.class)
public class XbdTaskExecutionAutoConfiguration {

	private XbdTaskExecutionProperties properties;

	public XbdTaskExecutionAutoConfiguration(XbdTaskExecutionProperties properties) {
		this.properties = properties;
	}

	@Bean
	public TaskExecutorCustomizer taskExecutorCustomizer() {
		return (threadPoolTaskExecutor) -> {
			XbdTaskExecutionProperties.Pool pool = this.properties.getPool();
			threadPoolTaskExecutor.setThreadGroup(
					new ThreadGroup(this.properties.getThreadGroupName()));
			threadPoolTaskExecutor.setWaitForTasksToCompleteOnShutdown(
					pool.isWaitForTasksToCompleteOnShutdown());
			threadPoolTaskExecutor
					.setAwaitTerminationSeconds(pool.getAwaitTerminationSeconds());
		};
	}

}
